package Test;


class MyBlockingqueue{
    //创建一个存放数据的个体
    private int [] data = new int[1000];
    //有效的元素个数
    private int size = 0;
    //队首下标
    private int head = 0;
    //队尾下标
    private int end = 0;

    //入队列
    public void put(int value){
        synchronized (this){
            if(size == data.length){
                //return;
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //把元素插入到end位置
            data[end] = value;
            end++;
            if(end >= data.length){
                end = 0;
            }
            //整体数组个数加一
            size++;
            //此处唤醒的是take中的wait
            this.notify();
        }
    }

    //出队列
    public Integer take(){
        synchronized (this){
            if(size == 0){
                //return null;
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //将要出的元素用ret接收
            int ret = data[head];
            head++;
            //判断如果超出数组元素就让head为0，从而形成循环
            if(head >= data.length){
                head = 0;
            }
            size--;
            //此处唤醒的是put中wait
            this.notify();
            return ret;
        }
    }
}
public class Test12 {
   private static MyBlockingqueue queue = new MyBlockingqueue();

    public static void main(String[] args) {
        //实现一个简单的生产者消费者模型
        Thread producer = new Thread(() ->{
            int num = 0;
            while(true){
                try {
                    System.out.println("生产了：" + num);
                    queue.put(num);
                    num++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
       producer.start();

       Thread customer = new Thread(() ->{
          while(true){
              try {
                  int num = queue.take();
                  System.out.println("消费了：" + num);
                  Thread.sleep(500);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
       });
       customer.start();
    }
}
